from tortoise.expressions import Q
from app.core.redis_base import delete_keys
from app.core.crud import CRUDBase
from app.models.appointment import AppointmentDesigner
from app.schemas.appointment import AppointmentDesignerCreate,AppointmentDesignerUpdate


class AppointmentDesignerController(CRUDBase[AppointmentDesigner, AppointmentDesignerCreate, AppointmentDesignerUpdate]):
    def __init__(self):
        super().__init__(model=AppointmentDesigner)

    async def do_create(self,request, obj_in: AppointmentDesignerCreate):
        await self.create(obj_in=obj_in)
        await self.do_delete_redis(request)
        return True

    async def do_update(self,request, obj_in: AppointmentDesignerUpdate):
        await self.update(id=obj_in.id, obj_in=obj_in)
        await self.do_delete_redis(request)
        return True

    async def do_delete(self,request, data_id: int):
        await self.remove(id=data_id)
        await self.do_delete_redis(request)
        return True

    async def do_list(self, page: int, page_size: int, search: Q = Q()):
        query = self.model.filter(search)
        total = await query.count()
        objs =  await query.offset((page - 1) * page_size).limit(page_size).order_by('-id')
        data = [await obj.to_dict() for obj in objs]
        return total, data

    async def do_detail(self,data_id:int):
        obj = await self.get(id=data_id)
        data = await obj.to_dict()
        return data

    @staticmethod
    async def do_delete_redis(request):
        await delete_keys("designers:*", request.state.redis)
        await delete_keys("dates:*", request.state.redis)
        await delete_keys("times:*", request.state.redis)
        await delete_keys("dates_ini:*", request.state.redis)
        await delete_keys("times_ini:*", request.state.redis)


appointment_designer_controller =AppointmentDesignerController()
